//
//  VoiceViewModel.swift
//  JiaoZiTaxi
//
//  Created by Hu Gang on 2022/11/28.
//

import AVFoundation
import Foundation

class VoiceViewModel: NSObject, ObservableObject, AVAudioPlayerDelegate {
   var audioRecorder: AVAudioRecorder!

   @Published var isRecording: Bool = false {
      willSet {
         print("[Voice] isRecording changed. \(newValue)")
         objectWillChange.send()
      }
   }

   // @Published
   var voiceFile: String?

   override init() {
      super.init()
   }

   func startRecording() {
      Task {
         let recordingSession = AVAudioSession.sharedInstance()
         do {
            try recordingSession.setCategory(.playAndRecord, mode: .spokenAudio, options: .defaultToSpeaker)
            try recordingSession.setActive(true, options: .notifyOthersOnDeactivation)
            try recordingSession.overrideOutputAudioPort(.speaker)
         } catch {
            print("Can not setup the Recording:\(error.localizedDescription)")
            return
         }

         let path = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
         let fileName = path.appendingPathComponent("voice_\(Date().toString).wav")

         self.voiceFile = fileName.relativePath

         let settings = [
            AVFormatIDKey: Int(kAudioFormatLinearPCM),
            AVSampleRateKey: 16000,
            AVNumberOfChannelsKey: 2,
            AVEncoderAudioQualityKey: AVAudioQuality.medium.rawValue
         ]

         do {
            self.audioRecorder = try AVAudioRecorder(url: fileName, settings: settings)
            self.audioRecorder.prepareToRecord()
            self.audioRecorder.record()

            DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
               self.isRecording = true
               print("[Voice] recoding......\(self.isRecording))")
            }
         } catch {
            print("[Voice] Failed to Setup the Recording:\(error.localizedDescription)")
         }
      }
   }

   func stopRecording() {
      Task {
         if let _ = audioRecorder {
            self.audioRecorder.stop()
         }
         DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
            self.isRecording = false
            print("[Voice] record stoped. \(self.isRecording))")
         }
      }
   }
}
